package ac.il.technion.c236369.hw4.core;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;

import ac.il.technion.c236369.hw4.configuration.ServerConfig;

public class WebServer {

	
	private List<Runnable> services = new ArrayList<Runnable>( );
	private ConnectionListener connectionListener = new ConnectionListener( );
	private ExecutorService pool = Executors.newCachedThreadPool( );
	private Logger log = Logger.getLogger( WebServer.class);
	private boolean terminated = false;
    /**
     * Initializes the Web server. This includes the the initialization of the
     * server socket, queues, threads and specific-type handlers.
     */
    public void initialize() {
    	for ( int i = 0; i < ServerConfig.getInstance().getProperties().getSocketReaders( ); ++i) {
    		services.add( new SocketReader( ));
    	}
    	for ( int i = 0; i < ServerConfig.getInstance().getProperties().getRequestHandlers(); ++i) {
    		services.add( new RequestHandler( ));
    	}
    };

    /**
     * Starts the server. Within this method, the threads are started and the server
     * socket starts listening.
     */
    public void start() {
    	
    	for( Runnable $ : services) 
    		pool.execute( $);
    	connectionListener.start( );
    	Runtime.getRuntime().addShutdownHook( new Thread() {
    		public void run( ) {
    			terminated = true;
    		}
    	});
    	while( !terminated) {
    		try {
				Thread.sleep(1 * 1000);
			} catch (InterruptedException e) {
				log.error(e);
			}
    	}
    	connectionListener.stopListen( );
    	pool.shutdown( );
    };
    
    public static void main(String[] args) {
		WebServer server = new WebServer( );
		server.initialize( );
		server.start();
	}
}